#include "sicasm.h"

//int proglen;
//INTFIELD intrec;
extern SYMTAB symtab;
char *line,*s;
int stad;
FILE *f,*obj;

char *makeaddr(char *s);
char *makesymaddr(int scode);
void initline(void);
void writeline(void);

void pass2(void)
{
 char *code,*s;
 int opfound,symcode;
 f=fopen("OUT.INT","rb");
 obj=fopen("CODE.OBJ","wt");
 fread(&intrec,sizeof(intrec),1,f);

 //HEADER RECORD
 fputc('H',obj);
 int i;
 for(i=0;i<6;i++) fputc(intrec.label[i],obj);
 fprintf(obj,"%s",makeaddr(itoa(intrec.addr,s,16)));
 fprintf(obj,"%s\n",makeaddr(itoa(proglen,s,16)));

 //TEXT RECORDS
 initline();
 do{
 code = new char[7];
 fread(&intrec,sizeof(intrec),1,f);
 opfound=opcodesearch(intrec.opcode);
 if (opfound>-1)
  {
     if (strcmp(intrec.operand,"        ")) //operand field not empty
       {
	 symcode=symtab.search(intrec.operand);
	 if (symcode==-1) //undefined symbol
	   {
	    symcode=0;
	    cout<<"\nError - Undefined Symbol: "<<intrec.operand;
	   }
       }
      else symcode=0;//operand field empty
    strcpy(code,itoa(opfound,s,16));
    strcat(code,makesymaddr(symcode));
  }
 else //opcode not found
  if ((!strcmp(intrec.opcode,"BYTE  ")) || (!strcmp(intrec.opcode,"WORD  ")))
    strcpy(code,"CODEXY");

 if(strlen(line)+6>69)
    {
      writeline();
      initline();
    }
 code[6]='\0';
 strcat(line,code);
 delete code;
 fread(&intrec,sizeof(intrec),1,f);
 } while(strcmp(intrec.opcode,"END   "));

 //END RECORD
 delete line;
 fputc('E',obj);
 fprintf(obj,"%s",makeaddr(itoa(startaddr,s,16)));

 fcloseall();
}

char *makeaddr(char *s)//to make width 6
{
 char *temp;
 int i;
 temp=new char[8];

 if(strlen(s)==6) strcpy(temp,s);
 else
 {
  for(i=0;i<6-strlen(s);i++)
  *(temp+i)='0';
  *(temp+i)='\0';

  strncat(temp,s,strlen(s));
 }
 return(strupr(temp));
}

char *makesymaddr(int scode)
{
 char temp[5],str[5];
 strcpy(temp,itoa(scode,s,16));
 switch (strlen(temp))
 {
  case 4:break;
  case 3:strcpy(str,"0");break;
  case 2:strcpy(str,"00");break;
  case 1:strcpy(str,"000");break;
 }
 strcat(str,temp);
 return (strupr(str));
}

void initline(void)
{
 line = new char[70];
 strcpy(line,"T");
 strcat(line,makeaddr(itoa(intrec.addr,s,16)));
 strcat(line,"  ");//reserved for record length
 stad=intrec.addr;
}

void writeline(void)
{
 char x[3];
 strcpy(x,strupr(itoa(intrec.addr-stad,s,16)));
 line[7]=x[0];
 line[8]=x[1];
 fprintf(obj,"%s\n",strupr(line));
 delete line;
}